//  热力图
let params = {
    mapCenter: [116.40, 40.10],
    krigingModel: 'exponential', //model还可选'gaussian','spherical' exponential
    krigingSigma2: 0,
    krigingAlpha: 226,
    maxValue: 20,
    canvasAlpha: 0.75, //canvas图层透明度
    colors: ['#680000', '#710000', '#7a0000', '#850000', '#8f0000', '#980000', '#a10000', '#aa0000', '#b60000', '#bf0000',
        '#ca0000', '#d30000', '#db0000', '#e50000', '#ee0000', '#f50000', '#f80000', '#fa0700', '#fa0f00', '#fa1500',
        '#fa1f00', '#fc2600', '#fd2e00', '#fc3600', '#fb3e00', '#fc4400', '#fd4c00', '#fc5400', '#fc5c00', '#fd6400',
        '#fd6c00', '#fc7500', '#fc7f00', '#fd8600', '#ff8d00', '#fe9600', '#fd9c00', '#fea300', '#feaa00', '#fcb400',
        '#fbbd00', '#fdc500', '#fdcd00', '#fbd500', '#fadd00', '#fbe601', '#fded03', '#fef502', '#fffc03', '#fbff07',
        '#f3fd0b', '#ebfd11', '#e3fd18', '#defc1c', '#d8fc22', '#cffe2d', '#c7fe37', '#c0fd3f', '#b7fd47', '#aefd4f',
        '#a5fd56', '#9ffd5d', '#97fd65', '#8bfd70', '#80fd79', '#78fd81', '#71fd88', '#6cfd90', '#66fd98', '#5ffc9f',
        '#55fca7', '#4bfdb2', '#44fdbb', '#3efcc2', '#35fcc9', '#2afed0', '#21fed7', '#1cfcdf', '#16fce8', '#0ffcf1',
        '#07fcf8', '#01fcfd', '#00f8fe', '#00f1fd', '#01e8fc', '#00e0fc', '#01d8fd', '#03d0fe', '#01c8fe', '#00c0fd',
        '#00b7fc', '#00aefc', '#00a6fd', '#00a0fc', '#009afd', '#0092ff', '#008afe', '#0081fd', '#0079fc', '#0070fd',
        '#0068fc', '#0061fb', '#0059fb', '#0050fd', '#0049fc', '#0041fc', '#003afd', '#0032fd', '#002afc', '#0022fa',
        '#001af9', '#0011f9', '#0009f9', '#0002f8', '#0000f6', '#0000f2', '#0000ea', '#0000e3', '#0000d8', '#0000cc',
        '#0000c2', '#0000b9', '#0000b0', '#0000a8', '#00009f', '#000094', '#00008a', '#000080', '#000074', '#000064'
    ].reverse()
};
let baseLayer = new ol.layer.Tile({
    title: "base",
    source: new ol.source.OSM()
});
let map = new ol.Map({
    target: 'map',
    layers: [baseLayer],
    view: new ol.View({
        center: params.mapCenter,
        projection: 'EPSG:4326',
        zoom: 10
    })
});
let WFSVectorSource = new ol.source.Vector();
let WFSVectorLayer = new ol.layer.Vector({
    source: WFSVectorSource,
});


let layerLabel = [];
//创建要素（可以使用data中的值， 也可随机）
for (let i = 0; i < 200; i++) {
    const value = Math.round(Math.random() * params.maxValue);
    let feature = new ol.Feature({
        // geometry: new ol.geom.Point([data.features[i].attributes.x, data.features[i].attributes.y]),
        // value: data.features[i].attributes.z
        //  下面采用随机值
        geometry: new ol.geom.Point([params.mapCenter[0] - (Math.random() * 10 > 5 ? 1 : -1) * Math.random() * 0.5, params.mapCenter[1] + (Math.random() * 10 > 5 ? 1 : -1) * Math.random() * 0.6]),
        value: value
    });
    feature.setStyle(new ol.style.Style({
        // image: new ol.style.Circle({
        //     radius: 6,
        //     fill: new ol.style.Fill({ color: "#00F" }),
        //     // opacity: 0.2
        // }),
        text: new ol.style.Text({
            textAlign: 'center', //位置-对齐方式
            textBaseline: 'bottom', //基准线  'bottom', 'top', 'middle', 'alphabetic', 'hanging', 'ideographic'.
            font: '16px Calibri, 黑体', //文字样式
            text: value + '', //文本内容
            fill: new ol.style.Fill({
                color: '#f00'
            }),
            stroke: new ol.style.Stroke({
                color: 'white',
                width: 1.5
            })
        })
    }));
    WFSVectorSource.addFeature(feature);
}


//定义裁剪边界
let coord = [polygonCoords];
let clipgeom = new ol.geom.Polygon(coord);

//绘制kriging插值图
let canvasLayer = null;
let drawKriging = function(extent) {
        let values = [],
            lngs = [],
            lats = [];
        WFSVectorSource.forEachFeature(function(feature) {
                values.push(feature.getProperties().value);
                lngs.push(feature.getGeometry().getCoordinates()[0]);
                lats.push(feature.getGeometry().getCoordinates()[1]);
            })
            // console.log(values.length)
        if (values.length > 3) {
            //    
            // console.log(values);
            // @TODO
            let letiogram = kriging.train(values, lngs, lats,
                params.krigingModel, params.krigingSigma2, params.krigingAlpha);

            let ex = clipgeom.getExtent();
            let grid = kriging.grid(coord, letiogram, (ex[2] - ex[0]) / 1000);
            //移除已有图层
            if (canvasLayer !== null) {
                map.removeLayer(canvasLayer);
            }
            //创建新图层
            canvasLayer = new ol.layer.Image({
                    source: new ol.source.ImageCanvas({
                        canvasFunction: (extent, resolution, pixelRatio, size, projection) => {
                            // console.log(extent);
                            // console.log(size);

                            let canvas = document.createElement('canvas');
                            canvas.width = size[0];
                            canvas.height = size[1];
                            canvas.style.display = 'block';
                            //设置canvas透明度
                            canvas.getContext('2d').globalAlpha = params.canvasAlpha;
                            //使用分层设色渲染
                            kriging.plot(canvas, grid, [extent[0], extent[2]], [extent[1], extent[3]], params.colors);
                            return canvas;
                        },
                        projection: 'EPSG:4326'
                    })
                })
                //向map添加图层
            map.addLayer(canvasLayer);
        } else {
            alert("有效样点个数不足，无法插值");
        }
    }
    //首次加载，自动渲染一次差值图
let extent = clipgeom.getExtent();
// console.log('边界', extent);

// 1、绘图
drawKriging(extent);
// 2、 显示数值
map.addLayer(WFSVectorLayer);

// 3、行政区
var feature = new ol.Feature({
    geometry: clipgeom,
});
const layer = new ol.layer.Vector({
    source: new ol.source.Vector({
        features: [feature]
    }),
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            width: 2,
            color: '#00f'
        }),
        // fill: new ol.style.Fill({
        //     color: [0, 0, 255, 0.6]
        // })
    })
})

map.addLayer(layer)